#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<pthread.h>
#include<unistd.h>
#include<fcntl.h>
#include<signal.h>
#include<ctype.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
//需求使用多线程提高服务器的并发量
#define SERVICEPORT 9527
struct client_addr{
    int fd;
    struct sockaddr_in clientaddr;
};
void*thread_fun(void*arg){
    struct client_addr*C=(struct client_addr*)arg;
    char buf[1024];
    //printf("ip:%s 端口号\n",C->clientaddr.sin_addr.s_addr,C->clientaddr.sin_port);
    while(1){
      int ret=read(C->fd,buf,sizeof(buf));
      if(ret==0){
           break;
      }
      write(STDOUT_FILENO,buf,sizeof(buf));
      int i=0;
      for(;i<ret;i++){
        buf[i]=toupper(buf[i]);
      }
      write(C->fd,buf,ret);
    }
    close(C->fd);
}
void sys_error(const char*s){
     perror(s);
     exit(-1);
}
int main(){
   int sfd,cfd;
   pthread_t pid;
   struct sockaddr_in saddr,caddr;
   saddr.sin_port=htons(SERVICEPORT);
   saddr.sin_addr.s_addr=htonl(INADDR_ANY);
   saddr.sin_family=AF_INET;
   sfd=socket(AF_INET,SOCK_STREAM,0);
   if(sfd==-1){
      sys_error("socket is error");
   }
   bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr));
   listen(sfd,128);
   while(1){
      int caddr_len=sizeof(caddr);
      cfd=accept(sfd,(struct sockaddr*)&caddr,&caddr_len);
      struct client_addr Clinetaddr;
      Clinetaddr.fd=cfd;
      Clinetaddr.clientaddr=caddr;
      pthread_create(&pid,NULL,thread_fun,(void*)&Clinetaddr);
      pthread_detach(pid);
    } 
   return 0;
}
